package com.compress4j.arithmetic.ppm;

import java.io.IOException;
import java.io.InputStream;

import com.compress4j.arithmetic.Arithmetic;
import com.compress4j.arithmetic.ArithmeticDecoder;

public class PPMInputStream extends InputStream{

	
	private ArithmeticDecoder decoder;
	private PPMTree<CompressionItem> ppmTree;
	
	public PPMInputStream(InputStream in) throws IOException{
		this(in,new PPMTree<CompressionItem>(in.read(),in.read(),CompressionItem.ALL_BYTE,new CompressionItem.Set()));
	}
	public PPMInputStream(InputStream in, PPMTree<CompressionItem> ppmTree) throws IOException{
		decoder = new Arithmetic.DeCoder(in);
		this.ppmTree = ppmTree;
	}
	private boolean eof = false;
	@Override
	public int read() throws IOException {
		if(eof) return -1;
		CompressionItem word = ppmTree.read(decoder);
		if(word==null){
			eof = true;
			return -1;
		}
		ppmTree.handleUsedItem(word);
		return word.getByte();
	}
	@Override
	public void close() throws IOException {
		decoder.close();
	}

	
	
}
